package gui;

import java.io.InputStream;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Dialogs;
import javafx.scene.control.Dialogs.DialogOptions;
import javafx.scene.control.Dialogs.DialogResponse;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
import jpsearchcore.RegionOfInterest;

public class Main extends Application {

	private Stage primaryStage;
	private BorderPane rootLayout;
	public InputStream is = getClass().getResourceAsStream("/icon.png");

	@Override
	public void start(Stage primaryStage) {
		this.primaryStage = primaryStage;
		this.primaryStage.setTitle("JPSearch Editor");		
		this.primaryStage.getIcons().add(new Image(is));
		
		primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>(){

			@Override
			public void handle(WindowEvent we) {				
				if(Dialogs.showConfirmDialog(null, "Are you sure you want to exit the application?",
						"Confirmation", "JPSearch Editor",DialogOptions.YES_NO) == DialogResponse.NO)
					we.consume();
			}
			
		});

		try {
			FXMLLoader loader = new FXMLLoader(Main.class.getResource("MainForm.fxml"));
			rootLayout = (BorderPane) loader.load();
			Scene scene = new Scene(rootLayout);
			primaryStage.setScene(scene);
			primaryStage.setResizable(false);
			primaryStage.show();
			Controller controller = loader.getController();
			controller.setMainApp(this);

		} catch (Exception e) {
			Dialogs.showErrorDialog(primaryStage, e.getMessage());
			return;
		}
	}
	
	/**
	 * Exits the application properly
	 */
	public void exitApplication(){
		if(Dialogs.showConfirmDialog(null, "Are you sure you want to exit the application?",
				"Confirmation", "JPSearch Editor",DialogOptions.YES_NO) == DialogResponse.YES)
			primaryStage.close();
	}

	/**
	 * Returns the main stage.
	 * @return
	 */
	public Stage getPrimaryStage() {
		return primaryStage;
	}

	/**
	 * Shows the Rule Generator
	 */
	public void showRuleGenerator() {
		try {
			// Load the fxml file and set into the center of the main layout
			FXMLLoader loader = new FXMLLoader(Main.class.getResource("RuleGenerator.fxml"));
			AnchorPane ruleGenPage = (AnchorPane) loader.load();
			Stage dialogStage = new Stage();
			dialogStage.setTitle("Rule Generator");
			is = getClass().getResourceAsStream("/icon.png");
			dialogStage.getIcons().add(new Image(is));
			dialogStage.initModality(Modality.NONE);
			dialogStage.setResizable(false);
			//dialogStage.initOwner(primaryStage);
			Scene scene = new Scene(ruleGenPage);
			dialogStage.setScene(scene);
			
			dialogStage.setOnCloseRequest(new EventHandler<WindowEvent>(){
				@Override
				public void handle(WindowEvent we) {				
					if(Dialogs.showConfirmDialog(null, "Are you sure you want to close Rule Generator?",
							"Confirmation", "Rule Generator",DialogOptions.YES_NO) == DialogResponse.NO)
						we.consume();
				}				
			});

			// Give the controller access to the main app
			RuleController controller = loader.getController();
			controller.setMainApp(this);
			controller.setDialogStage(dialogStage);

			// Show the dialog and wait until the user closes it
			dialogStage.show();

		} catch (Exception e) {
			// Exception gets thrown if the fxml file could not be loaded
			Dialogs.showErrorDialog(primaryStage, e.getMessage());
		}
	}

	/**
	 * Shows the Region tagging window
	 */
	public boolean showRegionTagging(RegionOfInterest roi, Image image, ImageView snapshot) {
		try {
			// Load the fxml file and set into the center of the main layout
			FXMLLoader loader = new FXMLLoader(Main.class.getResource("RegionTagging.fxml"));
			AnchorPane regionTaggingPane = (AnchorPane) loader.load();
			final Stage dialogStage = new Stage();
			dialogStage.setTitle("Region Tagging");
			dialogStage.initModality(Modality.WINDOW_MODAL);
			dialogStage.initOwner(primaryStage);
			dialogStage.initStyle(StageStyle.UTILITY);
			dialogStage.setResizable(false);
			Scene scene = new Scene(regionTaggingPane);
			dialogStage.setScene(scene);

			// Give the controller access to the main app
			RegionTaggingController controller = loader.getController();
			controller.setMainApp(this);
			controller.setDialogStage(dialogStage);
			controller.setRegionOfInterest(roi, image);
			
			//Close window with Escape key
			scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
		        public void handle(KeyEvent ke) {
		            if (ke.getCode() == KeyCode.ESCAPE) {
		                dialogStage.close();
		            }
		        }
		    });
			
			// Show the dialog and wait until the user closes it		    
			dialogStage.showAndWait();
			if(controller.isOkClicked())
				snapshot.setImage(controller.getSnapshot());

			return controller.isOkClicked();

		} catch (Exception e) {
			// Exception gets thrown if the fxml file could not be loaded
			//Dialogs.showErrorDialog(primaryStage, e.getMessage());
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * Shows the Metadat in XML format in a new window
	 */
	public void showXmlMetadata(String xml){
		try {
			// Load the fxml file and set into the center of the main layout
			FXMLLoader loader = new FXMLLoader(Main.class.getResource("XmlViewer.fxml"));
			AnchorPane xmlViewer = (AnchorPane) loader.load();
			final Stage dialogStage = new Stage();
			dialogStage.setTitle("JPSearch XML metadata");
			dialogStage.initModality(Modality.NONE);
			dialogStage.initOwner(primaryStage);
			dialogStage.initStyle(StageStyle.UTILITY);
			dialogStage.setResizable(true);
			Scene scene = new Scene(xmlViewer);
			dialogStage.setScene(scene);
			
			//Close window with Escape key
			scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
		        public void handle(KeyEvent ke) {
		            if (ke.getCode() == KeyCode.ESCAPE) {
		                dialogStage.close();
		            }
		        }
		    });

			// Give the controller access to the main app
			XmlViewerController controller = loader.getController();
			controller.setMainApp(this);
			controller.setDialogStage(dialogStage);
			controller.setXml(xml);

			// Show the dialog and wait until the user closes it		    
			dialogStage.showAndWait();

		} catch (Exception e) {
			// Exception gets thrown if the fxml file could not be loaded
			//Dialogs.showErrorDialog(primaryStage, e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * Shows the Date Editor window
	 */
	public boolean showDateEditor(TextField txtDate){
				
		try {
			// Load the fxml file and set into the center of the main layout
			FXMLLoader loader = new FXMLLoader(Main.class.getResource("DateEditor.fxml"));
			VBox dateEditor = (VBox) loader.load();
			final Stage dialogStage = new Stage();
			dialogStage.setTitle("Date Editor");
			dialogStage.initModality(Modality.WINDOW_MODAL);
			dialogStage.initOwner(primaryStage);
			dialogStage.initStyle(StageStyle.UTILITY);
			dialogStage.setResizable(false);
			Scene scene = new Scene(dateEditor);
			scene.getStylesheets().add("eu/schudt/javafx/controls/calendar/calendarstyle.css");
			dialogStage.setScene(scene);

			// Give the controller access to the main app
			DateEditorController controller = loader.getController();
			controller.setMainApp(this);
			controller.setDialogStage(dialogStage);
			controller.setInputDate(txtDate.getText());
			
			scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
		        public void handle(KeyEvent ke) {
		            if (ke.getCode() == KeyCode.ESCAPE) {
		                dialogStage.close();
		            }
		        }
		    });

			// Show the dialog and wait until the user closes it		    
			dialogStage.showAndWait();
			if(controller.isOkClicked())
				txtDate.setText(controller.getOutputDate());
				
			return controller.isOkClicked();

		} catch (Exception e) {
			// Exception gets thrown if the fxml file could not be loaded			
			e.printStackTrace();
		}
		return false;
	}

	public static void main(String[] args) {
		launch(args);
	}

}
